const moment = require('moment')
const { sequelize } = require('../core/db')
const { Sequelize, Model } = require('sequelize')
const Article = require('./Article')
const User = require('./User')

class Comment extends Model {}

Comment.init(
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    column_id: {
      type: Sequelize.INTEGER,
      allowNull: true,
      comment: '如果是回复其他人的，相对应的id'
    },
    column_user_id: {
      type: Sequelize.INTEGER,
      allowNull: true,
      comment: '回复别人的，别人的userid'
    },
    column_reading: {
      type: Sequelize.STRING(12),
      allowNull: true,
      defaultValue: 'false',
      comment: '是否已读'
    },
    content: {
      type: Sequelize.TEXT,
      allowNull: false,
      comment: '评论内容'
    },
    created_at: {
      type: Sequelize.DATE,
      allowNull: false,
      get() {
        return moment(this.getDataValue('created_at')).format('YYYY-MM-DD H:m')
      }
    },
    updated_at: {
      type: Sequelize.DATE,
      allowNull: false,
      get() {
        return moment(this.getDataValue('updated_at')).format('YYYY-MM-DD H:m')
      }
    }
  },
  {
    sequelize,
    modelName: 'comment',
    tableName: 'comments'
  }
)

Comment.hasMany(Comment, {
  foreignKey: 'column_id',
  targetKey: 'id',
  as: 'column'
})

Comment.belongsTo(Article, {
  foreignKey: 'article_id',
  targetKey: 'id',
  as: 'article'
})

Comment.belongsTo(User, {
  foreignKey: 'user_id',
  targetKey: 'id',
  as: 'user'
})

module.exports = Comment
